import utils from '@/components/utils'

/**
 * ECharts 图表实例集合
 */
const CHARTS_MAP = Object.create(null)

/**
 * 用于 setOption 的默认值
 */
const defaults = {}

let resizeInterval = 500

/**
 *
 * @param {Vue} component ECharts 组件实例
 */
async function resizeChart(component) {
  if (!component) {
    return
  }
  const chart = await component.getChart()
  if (!chart) {
    return
  }

  if (chart.isDisposed()) {
    return
  }

  try {
    chart.resize()
  } catch (e) {
    // eslint-disable-next-line
    console.warn(e.message)
  }
}

async function fixChartSize() {
  const now = new Date().getTime()
  for (const item of Object.values(CHARTS_MAP)) {
    const {component, size, ticks} = item

    const chart = await component.getChart()

    // 图表尚未渲染，忽略此操作
    if (!chart || chart.isDisposed()) {
      continue
    }

    if (now - ticks.resize < resizeInterval) {
      continue
    }

    ticks.resize = now

    if (!component.autoResize) {
      continue
    }

    const newSize = utils.getSize(component)
    // 检查容器大小是否发生了变化
    if (size.width !== newSize.width || size.height !== newSize.height) {
      item.size = newSize
      await resizeChart(component)
      continue
    }

    // 检查容器大小与 echarts 实例大小是否一致
    if (newSize.width !== chart.getWidth() || newSize.height !== chart.getHeight()) {
      await resizeChart(component)
    }
  }

  utils.wait(resizeInterval).then(fixChartSize)
}

fixChartSize()

// 设置全局通用的拦截器
const GLOBALS = {
  /**
   * @param {Object} options 原始的 options
   * @return {Object} 返回修改过的 options
   */
  interceptor: null
}

/**
 * 设置全局图表的 options 拦截器
 * @param {(Object)=>Object} interceptor 拦截器函数
 */
function setInterceptor(interceptor) {
  GLOBALS.interceptor = interceptor
}

export default {
  /**
   *
   * @param {Vue} component
   */
  add(component) {
    CHARTS_MAP[component.cid] = {
      ticks: {
        resize: 0
      },
      component,
      size: utils.getSize(component)
    }
  },
  /**
   *
   * @param {String} id
   * @return {Promise<null|echarts>}
   */
  async get(id) {
    const item = CHARTS_MAP[id]
    if (!item) {
      return null
    }
    return item.component.getChart()
  },
  /**
   *
   * @param {String} id
   */
  remove(id) {
    delete CHARTS_MAP[id]
  },
  /**
   *
   * @param {String} id
   */
  resize(id) {
    const item = CHARTS_MAP[id]
    if (!item) {
      return
    }
    resizeChart(item.component)
  },
  resizeAll() {
    for (const id in CHARTS_MAP) {
      resizeChart(CHARTS_MAP[id].component)
    }
  },
  setResizeInterval(timeout) {
    resizeInterval = timeout
  },
  /**
   * 默认的 echarts.setOption() 的选项
   * @return {{color: string|string[], backgroundColor: string|string[], animation: boolean, textStyle: Object, ...}}
   */
  get defaults() {
    return defaults
  },
  setInterceptor,
  getInterceptor() {
    return GLOBALS.interceptor
  }
}
